<template>
  <div class="page">
    <div class="form fxs">
      <img src="../../assets/loginT.jpg" />
      <div class="inputs">
        <h1>{{ VITE_NAME }}</h1>
        <el-form size="large" label-position="top" :model="loginForm" status-icon :rules="rules" ref="ruleFormRef" class="fromStyle">
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              :placeholder="t('login.username')"
              v-model="loginForm.username"
              autocomplete="off"
              class="inputwidth"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              :placeholder="t('login.pwd')"
              type="password"
              v-model="loginForm.password"
              autocomplete="off"
              class="inputwidth"
            />
          </el-form-item>
          <el-form-item>
            <el-button size="large" :loading="store.loading" style="width: 100%" type="primary" @click="submitForm">
              {{ t('login.login') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { VITE_NAME } from '~/api/index'
import { initRouteAndNav } from '~/utils/util'
import { Lock, User } from '@element-plus/icons-vue'

const { t } = useI18n()

const { ruleFormRef } = useRuleForm()
const loginForm = reactive({ username: '', password: '' })
const store = useAppStore()
const router = useRouter()
const rules = reactive({
  username: [{ required: true, message: t('common.input'), trigger: 'blur' }],
  password: [{ required: true, message: t('common.input'), trigger: 'blur' }]
})

const submitForm = async () => {
  ruleFormRef.value?.validate(async valid => {
    if (valid) {
      const oauth = await apis.api.loginToken({
        type: 'EMPLOYEE',
        grantType: 'password',
        scope: 'all',
        ...loginForm
      })
      store.initOauth(oauth)
      let user = await apis.api.loginOauth()
      store.initial(user)
      console.log('user', user)
      const menus = initRouteAndNav(user.authorities)
      store.initMenu(menus)
      router.push(store.defaultPage)
    }
  })
}
</script>

<style lang="scss" scoped>
.page {
  width: 100vw;
  position: relative;
  height: 100vh;
  overflow: hidden;
  background-repeat: 'no-repeat';
  background-size: 100% 100%;
}

.form {
  box-sizing: border-box;
  border-radius: 30px;
  background-color: #ffffff;
  overflow: hidden;
  width: 700px;
  margin: 0 auto;
  margin-top: calc((100vh - 400px) / 2);
  height: 400px;
  display: flex;

  img {
    width: 250px;
    height: 250px;
    padding-right: 40px;
  }

  padding: 30px;

  h1 {
    text-align: center;
  }

  .inputs {
    flex: 1;
  }

  h1,
  ::v-deep(.el-form-item) {
    margin-bottom: 32px;
  }
}

@media screen and (max-width: 480px) {
  .form {
    width: 300px;
  }
}
</style>
